/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: FragmentContainerLayout.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import io.bhex.baselib.R;
import io.bhex.baselib.utils.DebugLog;


/**
 * * 在addFragment时用来减少层级，尽量少的使用此布局进行其他操作，仅用来作为容器存在即可
 * ================================================
 */
public class FragmentContainerLayout extends RelativeLayout {

    /**
     * 缓存addView的Index
     */
    private int mAddIndex = 0;

    public FragmentContainerLayout(Context context) {
        super(context);
    }

    public FragmentContainerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FragmentContainerLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private OnHierarchyChangeListener listener = new OnHierarchyChangeListener() {
        @Override
        public void onChildViewAdded(View parent, View child) {
        }

        @Override
        public void onChildViewRemoved(View parent, View child) {
            if (child.getTag(R.id.fragment_container) != null && mAddIndex > 0)
                mAddIndex--;
        }
    };

    @Override
    public void addView(View child) {
        ViewGroup parent = (ViewGroup) getParent();
        parent.setOnHierarchyChangeListener(listener);
        if (parent != null) {
            mAddIndex++;
            parent.addView(child, parent.indexOfChild(this) + mAddIndex, getLayoutParams());
            child.setTag(R.id.fragment_container, new Object());
        } else
            super.addView(child);
    }

    @Override
    public void removeView(View view) {
        ViewGroup parent = (ViewGroup) getParent();
        if (parent != null && parent.indexOfChild(view) >= 0) {
            DebugLog.d("view index:" + parent.indexOfChild(view));
            parent.removeView(view);
        } else
            super.removeView(view);
    }
}
